package com.hsq.reflection.testReflection;


import org.junit.jupiter.api.Test;

import java.lang.reflect.Field;

public class ReflectAccessProperty {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<?> stuClass = Class.forName("com.hsq.reflection.testReflection.Student");
        Object o = stuClass.newInstance();
        Field age = stuClass.getField("age");
        age.set(o, 99);
        System.out.println(o);
        System.out.println(age.get(o));
        //使用反射获取private属性
        Field name = stuClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(o, "hsq");
        name.set(null, "hsq");//因为name是static属性，所o这个位置可以是空
        System.out.println(o);
        System.out.println(name.get(o));
        System.out.println(name.get(null));//要求name必须是静态属性
    }
    @Test
    public void test1() {
        System.out.println("----");
    }
}

class Student {
    public int age;
    private static String name;
    public Student() {

    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
}
